import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
// import Layout from '@/views/layout/index.vue'
import store from '@/store'
import { routes } from '@/router/routers'

Vue.use(VueRouter)

const router = new VueRouter({
  routes
})

// 路由前置守卫
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 只要有一级路由需要身份认证，就需要验证登录状态
    if (!store.state.user) {
      next({
        name: 'login',
        query: {
          redirect: to.fullPath // 把登录成功需要返回的页面告诉登录页面
        }
      })
    } else {
      next() // 允许通过
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

export default router
